/**
 * Created by PanJiaChen on 16/11/18.
 */

import i18n from '@/locales'
import dayjs from 'dayjs'

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
	if (arguments.length === 0) {
		return null
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
			time = parseInt(time)
		}
		if (typeof time === 'number' && time.toString().length === 10) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return [
				i18n.t('common.utils.day'),
				i18n.t('common.utils.one'),
				i18n.t('common.utils.two'),
				i18n.t('common.utils.three'),
				i18n.t('common.utils.four'),
				i18n.t('common.utils.five'),
				i18n.t('common.utils.six')
			][value]
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
	if (('' + time).length === 10) {
		time = parseInt(time) * 1000
	} else {
		time = +time
	}
	const d = new Date(time)
	const now = Date.now()

	const diff = (now - d) / 1000

	if (diff < 30) {
		return i18n.t('common.utils.recent')
	} else if (diff < 3600) {
		// less 1 hour
		return Math.ceil(diff / 60) + i18n.t('common.utils.minite_before')
	} else if (diff < 3600 * 24) {
		return Math.ceil(diff / 3600) + i18n.t('common.utils.hour_before')
	} else if (diff < 3600 * 24 * 2) {
		return i18n.t('common.utils.day_ago')
	}
	if (option) {
		return parseTime(time, option)
	} else {
		return (
			d.getMonth() +
			1 +
			i18n.t('common.utils.month') +
			d.getDate() +
			i18n.t('common.utils.day') +
			d.getHours() +
			i18n.t('common.utils.hour') +
			d.getMinutes() +
			i18n.t('common.utils.minite')
		)
	}
}

/**
 * excel格式校验
 * @param {file:file} file
 */
export function validateExcel(file) {
	if (!/\.(csv|xlsx|xls|XLSX|XLS)$/.test(file.name)) {
		return false
	}
	return true
}

/**
 * 给正负数加颜色
 * @param {numberVal} numberVal
 */
export function colorNum(numberVal) {
	let color = ''
	if (!numberVal) {
		return color
	}
	if (numberVal > 0) {
		color = 'danger'
	} else if (numberVal < 0) {
		color = 'success'
	}
	return color
}

/**
 * @desc 判断一个对象是否为空
 * @param {Object} obj 对象
 * @return {Boolean}
 */
export function checkNullObj(obj) {
	return !Object.keys(obj).length
}

export function isEmptyObj(val) {
	return !Object.keys(val).length && val.constructor === Object
}

/**
 * 判断输入的url是否正确
 * @param {String} str_url
 */
export function IsURL(str_url) {
	return /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(
		str_url
	)
}

/**
 * @desc 判断金额
 * @param {Number} num 数字
 */
export function isNum(num) {
	return /^(([1-9][0-9]*)|(([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2})))$/.test(num)
}

// 转化为百分比
export function changeToPercentage(point) {
	if (point) {
		let percent = Number(point * 100).toFixed(2)
		percent += '%'
		return percent
	}
}

// 时间转化成 hh:mm:ss格式
export function formatSeconds(value) {
	if (!value) {
		return '--:--:--'
	}

	let ss = parseInt(value)
	let mm = '00'
	let hh = '00'

	if (ss > 60) {
		mm = parseInt(ss / 60)
		ss = parseInt(ss % 60)

		if (mm > 60) {
			hh = parseInt(mm / 60)
			mm = parseInt(mm % 60)
		}
	}

	ss = parseInt(ss) >= 10 ? `${parseInt(ss)}` : `0${parseInt(ss)}`

	if (mm > 0) {
		mm = parseInt(mm) > 10 ? `${parseInt(mm)}` : `0${parseInt(mm)}`
	}
	if (hh > 0) {
		hh = parseInt(hh) > 10 ? `${parseInt(hh)}` : `0${parseInt(hh)}`
	}
	return `${hh}:${mm}:${ss}`
}

/**
 * 对象过滤空属性
 * @param {Object} obj 对象
 * @return {Object}
 */
export function filterEmptyParams(obj) {
	if (!Object.keys(obj).length) return obj
	const newPar = {}
	Object.keys(obj).map((item) => {
		if (
			obj[item] !== null &&
			obj[item] !== undefined &&
			obj[item].toString().replace(/(^\s*)|(\s*$)/g, '') !== ''
		) {
			newPar[item] = obj[item]
		}
	})
	return newPar
}
// 截取保留两位小数
export function formatTwoDecimalFull(num) {
	if (num === '') {
		return ''
	}
	const result = Number((num || 0).toString().match(/^\d+(?:\.\d{0,2})?/))
	let s_x = result.toString()
	let pos_decimal = s_x.indexOf('.')
	if (pos_decimal < 0) {
		pos_decimal = s_x.length
		s_x += '.'
	}
	while (s_x.length <= pos_decimal + 2) {
		s_x += '0'
	}
	return s_x
}

// blobDownload
export const blobDownload = (responses) => {
	return new Promise((resolve, reject) => {
		const result = responses.data || {}
		if (typeof result === 'object') {
			const { code, msg } = result
			if (code && code !== 200) {
				return reject(msg)
			}
		}
		if (!responses || !responses.headers) return reject(null)

		const disposition = responses.headers['content-disposition']
		const fileNames = disposition && disposition.split("''")
		const fileName = decodeURIComponent(fileNames?.[1] || '')
		const blob = new Blob([result], {
			type: 'application/octet-stream'
		})
		if ('download' in document.createElement('a')) {
			const downloadLink = document.createElement('a')
			downloadLink.download = fileName || ''
			downloadLink.style.display = 'none'
			downloadLink.href = URL.createObjectURL(blob)
			document.body.appendChild(downloadLink)
			downloadLink.click()
			URL.revokeObjectURL(downloadLink.href)
			document.body.removeChild(downloadLink)
		} else {
			window.navigator.msSaveBlob(blob, fileName)
		}
		return resolve()
	})
}

export const formatDatePicker = (dateTime, format = 'YYYY-MM-DD HH:mm:ss') => {
	const strDateTime = [undefined, undefined]

	if (dateTime) {
		const [start, end] = dateTime
		if (start && end) {
			strDateTime[0] = dayjs(start).format(format)
			strDateTime[1] = dayjs(end).format(format)
		}
	}
	return strDateTime
}

// 保留四位小数
export const filterSummar4 = (val) => {
	if (typeof val === 'number') {
		const toStr = val.toString()
		const str = toStr.indexOf('.')
		if (str !== -1) {
			return (
				toStr.substring(0, toStr.indexOf('.') + 5) - 0
			).toLocaleString('en-us', {
				minimumFractionDigits: 4,
				maximumFractionDigits: 4
			})
		} else {
			return val.toLocaleString('en-us', {
				minimumFractionDigits: 4,
				maximumFractionDigits: 4
			})
		}
	} else {
		return ''
	}
}

